#!/bin/bash
#Apocalypse backup created by Aviad Raviv for all users of Linux.
#It was created on Debian and assumes some configurations/utilities presents.
PATH=$PATH:/usr/sbin/
#################Prerequisites#################
if [ -z "$1" ]; then
	echo  "No settings file provided... bye bye"
	exit 1
else
	source $1
fi

if [[ -n "`which sendEmail`" && -n "`which tar`" && -n "`which logger`" && -n "`which date`" && -n "`which touch`" && -n "`which hostname`" && -n "`which lzma`" ]]; then
	export SENDEMAIL="`which sendEmail`" ; export TAR="`which tar`"; export LOGGER="`which logger`"; export TOUCH="`which touch`"; export HOSTNAME="`hostname`"; export LZMA="`which lzma`"; export XZ_OPT="-9e"; export XZ="`which xz`"
else
	echo -e "\nCould not determine the location of required programs, and will now exit.\nThis may be caused due to a missing Package, PATH or SUDO\nRequired utilities are:\nsendEmail; TAR; logger; date; touch; hostname; lzma\n"
	exit 1
fi
#################funcs#########################
logger_func()
{
$LOGGER -s -p local0.notice -t Hotfortech_Bash_Backup "$@"
if [ -w $LOG_FILE ]; then
	echo -e Hotfortech_Bash_Backup "$@" >> $LOG_FILE 2>&1
fi
}
email_admin_func()
{
if [[ -z $MAIL_TO || -z $FROM || -z $SUBJECT_PREFIX ]]; then
	logger_func "The email parameters are not set. Set them to be informed by email..."
return
fi

echo -e '<html>\n<head></head>\n<body>\n<p>\nHi '$MAIL_TO ' <br><br>' > $temp_email_file
echo -e $@ >> $temp_email_file
if [[ "$RUNNING" = "fin" && "$RUNNING" != "Started" ]] ; then
	echo -e ' <br>	Backup started at ' $START_TIME ' <br>\nBackup ended at' "`date`" ' <br>\n<br>To file ' $ASSEMBLED_FILE_NAME ' <br><br><br>\n(This message was generated by a horde of GNU elfs)<br></p></body></html>' >> $temp_email_file
else
	if [[ -e $LOG_FILE && "$RUNNING" != "Started" ]] ; then
		echo -e ' <br>	Backup started at ' $START_TIME ' <br><br>\nTo file ' $ASSEMBLED_FILE_NAME ' <br><br><br>The log file output is:<br><br></p></body></html>' >> $temp_email_file
	fi
fi
	if [ "$RUNNING" = "Started" ] ; then
		$SENDEMAIL -f "$FROM" -t "$MAIL_TO" -u "$SUBJECT_PREFIX - $SUBJECT_MATTER" -a -s "$SMATRHOST" -q -o message-file=$temp_email_file
	else
		$SENDEMAIL -f "$FROM" -t "$MAIL_TO" -u "$SUBJECT_PREFIX - $SUBJECT_MATTER" -a "$LOG_FILE" -s "$SMATRHOST" -q -o message-file=$temp_email_file
	fi
	logger_func "Sent an Email to the Admin about $RUNNING"
}
email_logger_func()
{
	logger_func "$@"
	email_admin_func "$@"
}
BSOD()
{
	export SUBJECT_MATTER="BSOD"
	RUNNING="BSOD"
	email_logger_func "There was an <big><big><font color="red">exception</font></big></big> when running the CVTd backup script on $HOSTNAME T_T"""
}

exit_status()
{
if [ $1 -ne 0 ]; then
		export SUBJECT_MATTER="$2 FAILED"
			if [ -w $temp_email_file ];then
				email_logger_func $3
			else
				logger_func $@
			fi
		logger_func "exit_status function recived a non-zero exit value from the last executed command which was recived from $RUNNING and will now exit"
		exit 1
else
	logger_func $2 "Was successful"
fi
}
scripts_func()
{
RUNNING="$1"
if [[ -z "$2" ]];then
	return
else
	logger_func "Executing $RUNNING script: "
	if [ -w $temp_email_file ];then
		$2 >> $LOG_FILE 2>&1
	else
		$2
	fi
	exit_status $? "$RUNNING" "The backup script on <big>$HOSTNAME <big><font color="red">FAILED</font></big></big> to execute the $RUNNING script"
fi
}

RUNNING="Touching tmp files"
export temp_email_file=/tmp/email.txt
$TOUCH $temp_email_file
exit_status $? "$RUNNING - temp email files" "Touching temp email file <font color="red">FAILED</font>"
if [ -n "$WHERE_TO_BACKUP_TO" ]; then
	$TOUCH $WHERE_TO_BACKUP_TO/prob.tmp
	exit_status $? "$RUNNING - probing the where to backup to directory" "Touching WHERE_TO_BACKUP_TO directory <font color="red">FAILED</font>"
	[ -e $WHERE_TO_BACKUP_TO/prob.tmp ] && rm -f $WHERE_TO_BACKUP_TO/prob.tmp
	exit_status $? "$RUNNING - deleting the prob" "Touching was unable to delete the WHERE_TO_BACKUP_TO prob file <font color="red">FAILED</font>"
	else 
	logger_func "The were_to_backup_to parameter was not set"
fi

###############################################
#trap 'BSOD' ERR
###############################################
export START_TIME="`date`"
export SUBJECT_MATTER="Started"
RUNNING="Started"
email_logger_func "<big>Starting</big> the backup script on $HOSTNAME at $START_TIME"
###############################################

##################pre script###################
scripts_func "PRE" "$PRE_SCRIPT"
##################eng##########################
scripts_func "AUX" "$AUX_SCRIPT"
RUNNING="Watcher Verification"

case $BACKUP_CYCLE in
			day)	export DAY="`date +%A`"
					logger_func "The daily retention plan, was explicitly specified."
				;;
			month)	export DAY="`date +%d`"
					logger_func "The monthly retention plan, was explicitly specified."
				;;
			year)	export DAY="`date +%j`"
					logger_func "The yearly retention plan, was explicitly specified."
				;;
			*)		export DAY="`date +%A`"
					logger_func "The daily retention plan, was implicit."
				;;
esac

		
logger_func "Performing the watcher verification segment"
RUNNING="Watcher verification segment"
if [ -z "$WHERE_TO_BACKUP_TO" ] ; then
	if [ -n "$WATCH_DIR" ] ; then 
	logger_func "This script is only set to watch another backup"
	else
	logger_func "???I dont know what this script is setup to do... no where to backup and nothing to watch????"
	fi
else
	if [ -z "`find $WHERE_TO_BACKUP_TO -type f`" ] ; then
		logger_func "Listing the where_to_backup_to directory was empty, this should only appear for the first run"
	else
		if [ -n "`find $WHERE_TO_BACKUP_TO -type f -mtime -2`" ]; then
			logger_func "The last backup was was created less then 2 days ago"
		else
			export SUBJECT_MATTER="Warning!! missing backup files!"
			email_logger_func "The last backup file is <big><font color="red">older then 2 days</font></big>!!!"
		fi
	fi
fi	
	
if [ -n "$WHAT_TO_BACKUP" ]; then
RUNNING="TAR parameters check"
logger_func "Executing the TAR segment"
	if [[ -n $WHERE_TO_BACKUP_TO && -n $BACKUP_FILE_NAME_PREFIX && -n $DAY ]]; then
		export ASSEMBLED_FILE_NAME=$WHERE_TO_BACKUP_TO$BACKUP_FILE_NAME_PREFIX$DAY.tar.gz
		logger_func "The backup file was set to $ASSEMBLED_FILE_NAME"
	else
		exit_status $? "$RUNNING" "The TAR parameters <font color="red">not initialized</font>"
	fi
	RUNNING="TARing"
		if [ -z "$EXCLUDE_FROM_BACKUP" ]; then
			if [ -w $LOG_FILE ]; then
			$TAR $TAR_COMPRESS -cvhf $ASSEMBLED_FILE_NAME $WHAT_TO_BACKUP >> $LOG_FILE 2>&1
			else
			$TAR $TAR_COMPRESS -cvhf $ASSEMBLED_FILE_NAME $WHAT_TO_BACKUP
			fi
		else
			for i in $EXCLUDE_FROM_BACKUP; do
			EX="$EX --exclude $i"
			done
			if [ -w $LOG_FILE ]; then
				$TAR $TAR_COMPRESS -cvhf $ASSEMBLED_FILE_NAME $WHAT_TO_BACKUP $EX >> $LOG_FILE 2>&1
			else
				$TAR $TAR_COMPRESS -cvhf $ASSEMBLED_FILE_NAME $WHAT_TO_BACKUP $EX
			fi
		fi
	exit_status $? "$RUNNING" "<big><font color="red">FAILED</font></big> to execute the TAR on $HOSTNAME :("
	if [ $TAR_COMPRESS = "--lzma" ]; then
	RUNNING="LZMA Integrety check"
	logger_func "Executing the LZMA verify segment"
		if [ -n "$XZ" ] ; then
			logger_func "Found xz-utils on the system, so using them to perform the integrety check"
			if [ -w $LOG_FILE ]; then
				$XZ -t -v $ASSEMBLED_FILE_NAME >> $LOG_FILE 2>&1
			else
				$XZ -t -v  $ASSEMBLED_FILE_NAME
			fi
		else
			logger_func "looks like an old version of LZMA is used on this system, so using LZMA to perform the integrety check"
			if [ -w $LOG_FILE ]; then
				$LZMA -t -v $ASSEMBLED_FILE_NAME >> $LOG_FILE 2>&1
			else
				$LZMA -t -v $ASSEMBLED_FILE_NAME
			fi
		fi
	exit_status $? "$RUNNING" "<big><font color="red">FAILED</font></big> to execute the integrety check of $ASSEMBLED_FILE_NAME for $HOSTNAME :("
	fi
	else
	logger_func "No TAR location was specified, so TAR segment was skipped."
fi

if [[ -n $WATCH_DIR && -n $DAYS_TO_RETAIN ]]; then
RUNNING="Watcher cleanup retention"
	logger_func "Performing the watcher retention segment"
	if [ -w $LOG_FILE ]; then
			find $WATCH_DIR -type f -mtime +$DAYS_TO_RETAIN -ls -delete >> $LOG_FILE 2>&1
			else
			find $WATCH_DIR -type f -mtime +$DAYS_TO_RETAIN -ls -delete
			fi
			exit_status $? "$RUNNING" "<big><font color="red">Watching FAILED</font></big> to execute, on $HOSTNAME :("
else
	logger_func "No directories to watch for cleanup"
fi
	


##############################################

###################psot script#################
scripts_func "POST" "$POST_SCRIPT"
###############FIN & clean up########################
export SUBJECT_MATTER="Succeeded"
RUNNING="fin"
email_logger_func "The backup on $HOSTNAME was "'<big><big><font color="green">successful ^_^</font></big></big><br>'
[ -e $temp_email_file ] && rm $temp_email_file
